<template>
  <el-dialog
    :visible.sync="isVisible"
    :title="addJinDialog.title"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :modal-append-to-body="false"
    @close="closeDialog"
  >
    <div class="form">
      <el-form
        ref="form"
        :model="form"
        :rules="form_rules"
        :label-width="dialog.formLabelWidth"
        style="margin: 10px; width: auto"
      >
        <el-form-item label="名称" prop="">
          <el-select
            :disabled="type == 'view'"
            v-model="form.id"
            clearable
            filterable
            remote
            @change="changeVal($event)"
            :remote-method="getFormList"
            placeholder="请输入车辆名称"
          >
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item prop="pic" label="产品图片">
          <el-upload
            list-type="picture-card"
            :headers="token"
            action="#"
            accept="image/*"
            :http-request="httpRequest"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :before-upload="beforeUploadFile"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="" />
          </el-dialog>
        </el-form-item> -->
        <el-form-item class="text_right">
          <el-button @click="isVisible = false">取 消</el-button>
          <el-button type="primary" @click="onSubmit('form')">提 交</el-button>
        </el-form-item>
      </el-form>
    </div>
  </el-dialog>
</template>

<script>
import { mapState, mapGetters } from "vuex";
import axios from "axios";

import { register, categorysearch } from "@/api/user";
import { qualitychange } from "@/api/common";
import AreaJson from "@/assets/datas/area.json";
import { getToken } from "@/utils/auth";
export default {
  name: "addFundDialogs",
  data() {
    let validateData = (rule, value, callback) => {
      if (value === "") {
        let text;
        if (rule.field == "income") {
          text = "收入";
        } else if (rule.field == "pay") {
          text = "支出";
        } else if (rule.field == "accoutCash") {
          text = "账户现金";
        }
        callback(new Error(text + "不能为空~"));
      } else {
        let numReg = /^[0-9]+.?[0-9]*$/;
        if (!numReg.test(value)) {
          callback(new Error("请输入正数值"));
        } else {
          callback();
        }
      }
    };
    return {
      dialogImageUrl: "",
      dialogVisible: false,
      disabled: false,
      areaData: [],
      isVisible: this.isShow,
      baseUrl: "localhost:8000/updateimg",
      token: {
        Authorization: getToken("Token"),
      },
      options: [],
      loading: false,
      form: {},
      payType: [
        { label: "提现", value: "0" },
        { label: "提现手续费", value: "1" },
        { label: "提现锁定", value: "2" },
        { label: "理财服务退出", value: "3" },
        { label: "购买宜定盈", value: "4" },
        { label: "充值", value: "5" },
        { label: "优惠券", value: "6" },
        { label: "充值礼券", value: "7" },
        { label: "转账", value: "8" },
      ],
      form_rules: {
        username: [
          { required: true, message: "用户名不能为空！", trigger: "blur" },
        ],
        income: [{ required: true, validator: validateData, trigger: "blur" }],
        pay: [{ required: true, validator: validateData, trigger: "blur" }],
        accoutCash: [
          { required: true, validator: validateData, trigger: "blur" },
        ],
        incomePayType: [
          { required: true, message: "请选择收支类型", trigger: "change" },
        ],
        address: [{ required: true, message: "请选择籍贯", trigger: "change" }],
      },
      //详情弹框信息
      dialog: {
        width: "400px",
        formLabelWidth: "120px",
      },
    };
  },
  props: {
    isShow: Boolean,
    dialogRow: Object,
  },
  computed: {
    ...mapGetters(["addJinDialog"]),
  },
  created() {
    this.areaData = AreaJson;
  },
  mounted() {
    if (this.addJinDialog.type === "edit") {
      this.form = this.dialogRow;
      // console.log(this.form);
      // this.form.incomePayType = this.dialogRow.incomePayType.toString();
      // this.form.address = ["120000", "120200", "120223"]
    } else {
      this.$nextTick(() => {
        this.$refs["form"].resetFields();
      });
    }
  },
  methods: {
    getFormList(query) {
      if (query !== "") {
        this.loading = true;
        let children = [];
        let obj = {
          opcode: "Int16Array",
          children: children,
          name: query,
          page: 1,
          pagesize: 10,
        };
        categorysearch(obj).then((res) => {
          this.loading = false;
          this.options = res.data.data;
        });
      } else {
        this.options = [];
        console.log("111");
      }
    },
    changeVal(event) {
      // let arr = this.options.filter((item) => {
      //   return item.address == event;
      // });
      // this.form.longitude = arr[0].location.lng;
      // this.form.latitude = arr[0].location.lat;
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    beforeUploadFile(file) {
      console.log("before upload");
      console.log(file);
      let extension = file.name.substring(file.name.lastIndexOf(".") + 1);
      let size = file.size / 1024 / 1024;
      //   if (extension !== "xlsx") {
      //     this.$notify.warning({
      //       title: "警告",
      //       message: `只能上传Excel2017（即后缀是.xlsx）的文件`,
      //     });
      //   }
      //   if (size > 10) {
      //     this.$notify.warning({
      //       title: "警告",
      //       message: `文件大小不得超过10M`,
      //     });
      //   }
      return true;
    },
    httpRequest(data) {
      let param = new FormData(); // 创建form对象
      param.append("filePath", data.file); // 通过append向form对象添加数据
      let config = {
        headers: {
          "Content-Type": "multipart/form-data",
          Authorization: getToken("Token"),
        },
      };
      axios.post("/updateimg", param, config).then((res) => {
        if (res.data.success) {
          this.form.pic = this.form.pic + (res.data.data[0] + ":");
          this.form.minipic = this.form.minipic + (res.data.data[0] + ":");
        }
      });
    },
    handleRemove(file) {
      console.log(file);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleDownload(file) {
      console.log(file);
    },
    getCascaderObj(val, opt) {
      return val.map(function (value, index, array) {
        for (var item of opt) {
          if (item.value == value) {
            opt = item.children;
            return item.label;
          }
        }
        return null;
      });
    },
    handleChange(value) {
      console.log([...value]); // ["120000", "120200", "120223"]
      this.form.address = [...value];
      let vals = this.getCascaderObj([...value], this.areaData); // arr
      this.form.tableAddress = vals.join(",").replace(/,/g, "");
    },
    closeDialog() {
      this.$emit("closeDialog");
    },
    //表单提交
    onSubmit(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          //表单数据验证完成之后，提交数据;
          let formData = this[form];
          const para = Object.assign({}, formData);

          // edit
          if (this.addJinDialog.type === "edit") {
            updateMoney(para).then((res) => {
              this.$message({
                message: "修改成功",
                type: "success",
              });
              this.$refs["form"].resetFields();
              this.isVisible = false;
              this.$emit("getFundList");
            });
          } else {
            // add
            let obj = {
              ...this.form,
              quality: 1,
            };
            qualitychange(obj).then((res) => {
              this.$message({
                message: "新增成功",
                type: "success",
              });
              this.$refs["form"].resetFields();
              this.isVisible = false;
              this.$emit("getFundList");
            });
          }
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.search_container {
  margin-bottom: 20px;
}
.btnRight {
  float: right;
  margin-right: 0px !important;
}
.searchArea {
  background: rgba(255, 255, 255, 1);
  border-radius: 2px;
  padding: 18px 18px 0;
}
</style>
